package com.eastfair.venuebooking.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.eastfair.annotation.annotation.base.BaseControllerInfo;
import com.eastfair.annotation.annotation.log.SysLog;
import com.eastfair.annotation.annotation.security.PreAuth;
import com.eastfair.boot.controller.SuperController;
import com.eastfair.boot.request.PageParams;
import com.eastfair.core.base.R;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.echo.core.EchoService;
import com.eastfair.venuebooking.demand.ContactGroup;
import com.eastfair.venuebooking.dto.*;
import com.eastfair.venuebooking.entity.Contact;
import com.eastfair.venuebooking.service.ContactRefService;
import com.eastfair.venuebooking.service.ContactService;
import com.eastfair.venuebooking.vo.ContactVO;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * <p>
 * 前端控制器
 * 客户及线索联系人表
 * </p>
 *
 * @author linan
 * @date 2022-06-08
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/contact")
@Api(value = "Contact", tags = "客户及线索联系人表")
@PreAuth(replace = "venuebooking:contact:")
public class ContactController extends SuperController<ContactService, Long, Contact, ContactPageQuery, ContactSaveDTO, ContactUpdateDTO> {

    @Autowired
    private EchoService echoService;

    @Resource
    private ContactService contactService;

    @Resource
    private ContactRefService contactRefService;

    @Override
    public void handlerResult(IPage<Contact> page) {
        // 想让返回值实现自动回显，请将此行代码打开
        // echoService.action(page);
    }

    /**
     * Excel导入后的操作
     *
     * @param list
     */
    @Override
    public R<Boolean> handlerImport(List<Map<String, String>> list) {
        List<Contact> contactList = list
                .stream()
                .map((map) -> Contact.builder().build())
                .collect(Collectors.toList());
        return R.success(baseService.saveBatch(contactList));
    }

    /**
     * 处理参数
     *
     * @param params 分页参数
     */
    @Override
    public void handlerQueryParams(PageParams<ContactPageQuery> params) {
        ContactPageQuery pageQuery = params.getModel();
        //分页处理
        if (ContextUtil.getProjectId() != null) {
            pageQuery.setProjectId(ContextUtil.getProjectId());
        }
    }

    /**
     * 分页查询联系人.
     *
     * @param pageParams the query
     * @return the r
     */
    @PostMapping("/page/contact")
    @BaseControllerInfo(voGroup = {ContactGroup.QueryContact.class})
    public R<IPage<ContactVO>> queryContact(@RequestBody PageParams<ContactQuery> pageParams) throws Exception {
        log.info("pageContact - 分页查询联系人, pageParams={}", pageParams);

        IPage<ContactVO> page = contactService.listContactVOs(pageParams);
        return R.successDef(page);
    }

    /**
     * id 查询联系人信息.
     *
     * @param id the id
     * @return the r
     */
    @GetMapping("/get/{id}")
    public R<ContactVO> getById(@PathVariable("id") Long id) {
        log.info("getById - id获取详情, id={}", id);

        return R.successDef(contactService.getContactVOById(id));
    }

    /**
     * 新增联系人.
     *
     * @param saveDTO the save dto
     * @return the r
     */
    @SysLog("新增联系人")
    @PostMapping("/save")
    public R<Boolean> saveContact(@RequestBody @Validated({ContactDTO.Save.class}) ContactDTO saveDTO) {
        log.info("saveContact - 新增联系人, saveDTO={}", saveDTO);

        return R.successDef(contactService.saveContact(saveDTO));
    }

    /**
     * 修改联系人.
     *
     * @param updateDTO the save dto
     * @return the r
     */
    @SysLog("修改联系人")
    @PostMapping("/update")
    public R<Boolean> updateContact(@RequestBody @Validated({ContactDTO.Update.class, ContactDTO.Save.class})
                                            ContactDTO updateDTO) {
        log.info("updateContact - 修改联系人, updateDTO={}", updateDTO);

        return R.successDef(contactService.updateContact(updateDTO));
    }

    /**
     * 移除联系人.
     *
     * @param ids the ids
     * @return the r
     */
    @SysLog("移除联系人")
    @PostMapping("/remove")
    public R<Boolean> deleteContact(@RequestBody @NotEmpty(message = "联系人id列表不可为空") List<Long> ids) {
        log.info("removeContact - 移除联系人, ids={}", ids);

        return R.successDef(contactService.removeContactByIds(ids));
    }

    /**
     * 设为首要联系人.
     *
     * @return the r
     */
    @SysLog("设为首要联系人")
    @PostMapping("/important")
    public R<Boolean> updateImportant(@RequestBody @Validated({ContactRefDTO.Important.class}) ContactRefDTO updateDTO) {
        log.info("important - 设为首要联系人, updateDTO={}", updateDTO);

        return R.successDef(contactRefService.updateImportant(updateDTO));
    }

    /**
     * 查询待同步到cms的联系人.
     *
     * @return the r
     */
    @GetMapping("/cms/sync")
    public R<List<ContactVO>> queryForSyncCms() {
        log.info("queryForSyncCms - 查询待同步到cms的联系人");
        return R.successDef(contactService.listWaitCmsSync());
    }

    /**
     * 更新cms状态已同步.
     *
     * @param ids the ids
     * @return the r
     */
    @PostMapping("/update/crm/sync")
    public R<Boolean> updateHasSyncCrm(@RequestBody List<Long> ids) {
        log.info("updateHasSyncCms - 更新cms状态已同步, ids={}", ids);
        return R.successDef(contactService.updateCrmHasSync(ids));
    }

    /**
     * 导出联系人.
     *
     * @param contactQuery the contact query
     * @param response     the response
     * @throws Exception the exception
     */
    @PostMapping("/export")
    public void exportContact(@RequestBody ContactQuery contactQuery, HttpServletResponse response) throws Exception {
        log.info("exportContact - 导出联系人, contactQuery={}", contactQuery);
        contactService.exportContact(contactQuery, response);
    }
}
